<?php
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    
    if (!$userId) {
        echo json_encode(['status' => 'error', 'message' => '用户ID不能为空']);
        exit;
    }
    
    // 检查是否有文件上传
    if (!isset($_FILES['avatar'])) {
        echo json_encode(['status' => 'error', 'message' => '请选择头像']);
        exit;
    }
    
    $avatar = $_FILES['avatar'];
    
    // 验证文件类型
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
    if (!in_array($avatar['type'], $allowedTypes)) {
        echo json_encode(['status' => 'error', 'message' => '只支持JPG、PNG、GIF格式的图片']);
        exit;
    }
    
    // 验证文件大小（最大 5MB）
    if ($avatar['size'] > 5 * 1024 * 1024) {
        echo json_encode(['status' => 'error', 'message' => '图片大小不能超过5MB']);
        exit;
    }
    
    // 设置上传目录
    $uploadDir = __DIR__ . '/uploads/avatars/';
    
    // 检查并创建目录
    if (!file_exists($uploadDir)) {
        if (!mkdir($uploadDir, 0777, true)) {
            echo json_encode(['status' => 'error', 'message' => '服务器配置错误']);
            exit;
        }
    }
    
    // 生成新的文件名
    $fileExtension = strtolower(pathinfo($avatar['name'], PATHINFO_EXTENSION));
    $newFileName = date('YmdHis') . '_' . uniqid() . '.' . $fileExtension;
    $avatarPath = 'uploads/avatars/' . $newFileName;
    $fullPath = $uploadDir . '/' . $newFileName;
    
    // 移动上传的文件
    if (move_uploaded_file($avatar['tmp_name'], $fullPath)) {
        // 更新用户头像路径
        $sql = "UPDATE users SET avatar = ? WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("si", $avatarPath, $userId);
        
        if ($stmt->execute()) {
            echo json_encode([
                'status' => 'success',
                'message' => '头像上传成功',
                'image_url' => $avatarPath
            ]);
        } else {
            unlink($fullPath);
            echo json_encode(['status' => 'error', 'message' => '头像更新失败']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => '文件保存失败']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => '不支持的请求方法']);
}

$conn->close();
?> 